package com.xinghua.web;

import com.xinghua.web.mysqldb.XingHuadb;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import javax.swing.*;
import java.awt.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class XinghuaWeb extends XingHuadb {
    private static WebDriver driver;
    private static final String HttpUrl = "http://www.xinhuanet.com/legal/ej.htm?page=fzzt";
    private static final String UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0";
    private static final String AcceptLanguage = "en,zh-CN;q=0.9,zh-TW;q=0.8,zh;q=0.7";
    private static final String TitleXPath = "/html/body/div[4]/div/div[1]/div/a[5]";
    private static GuiInterface guiInterface;

    public static void main(String[] args) {
        guiInterface = new GuiInterface();
        guiInterface.display();
    }

    public static void startCrawling() {
        if (requested()) {
            appendText("开始执行\n");
            initializeDriver();
            driver.get(HttpUrl);
            WebElement headerTitle = driver.findElement(By.xpath(TitleXPath));
            appendText("标题：" + headerTitle.getText() + "\n----------------------------------------------------------------------------------------\n");
            // 创建并启动高优先级线程，负责点击"加载更多"
            new Thread(new HighPriorityTask(), "High Priority Thread").start();
            // 创建并启动低优先级线程，负责处理新闻信息
            new Thread(new LowPriorityTask(), "Low Priority Thread").start();
        }
    }

    public static void appendText(String text) {
        guiInterface.appendText(text);
    }

    private static void initializeDriver() {
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--headless");
        options.addArguments("--disable-gpu");
        System.setProperty("webdriver.chrome.driver", "./chromedriver_131.0.6778.69_x32.exe");
        driver = new ChromeDriver(options);
    }
//初始化请求测试网站是否能访问
    public static boolean requested() {
        try {
            URL urlObj = new URL(HttpUrl);
            HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
            connection.setRequestProperty("User-Agent", UserAgent);
            connection.setRequestProperty("Accept-Language", AcceptLanguage);
            int responseCode = connection.getResponseCode();
            appendText("Response Code: " + responseCode + "\n");
            return responseCode == 200;
        } catch (Exception e) {
            appendText("请求过程中发生异常：" + e.getMessage() + "\n");
            return false;
        }
    }
//初始化界面加载全部页面
    static class HighPriorityTask implements Runnable {
        @Override
        public void run() {
            int x = 0;
            while (x < 40) {
                x++;
                if (x % 11 == 0) {
                    try {
                        Thread.sleep(1000);
                        driver.findElement(By.xpath("//div[@class='xpage-more-btn']")).click();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
//打印页面的所有新闻
    static class LowPriorityTask implements Runnable {
        XingHuadb xinghuadb = new XingHuadb();

        @Override
        public void run() {
            int i = 0;
            while (i < 20) {
                try {
                    Thread.sleep(1000);
                    i++;
                    appendText("第" + i + "条新闻\n");
                    String center_xpath = "/html/body/div[4]/div/div[2]/div/div/ul/li[" + i + "]/div[2]/div[1]/a";
                    WebElement center = driver.findElement(By.xpath(center_xpath));
                    appendText("内容：" + center.getText() + "\n");
                    String time_xpath = "/html/body/div[4]/div/div[2]/div/div/ul/li[" + i + "]/div[2]/div[2]/div";
                    WebElement timer = driver.findElement(By.xpath(time_xpath));
                    appendText("时间：" + timer.getText() + "\n");
                    if (guiInterface.isImportToDatabase()) {
                        xinghuadb.insert(timer.getText(), center.getText());
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException(e);
                }
            }
        }
    }
//GUI渲染
    public static class GuiInterface {
        private JFrame frame;
        private JTextArea textArea;
        private JButton startButton;
        private JCheckBox importToDatabaseCheckbox;

        public GuiInterface() {
            initialize();
        }

        private void initialize() {
            frame = new JFrame("新华网爬虫");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(600, 400);
            frame.setLayout(new BorderLayout());

            textArea = new JTextArea();
            textArea.append("开始获取");
            textArea.setEditable(false);
            frame.add(new JScrollPane(textArea), BorderLayout.CENTER);

            JPanel buttonPanel = new JPanel();
            startButton = new JButton("开始爬取");
            startButton.addActionListener(e -> startCrawling());
            buttonPanel.add(startButton);

            importToDatabaseCheckbox = new JCheckBox("导入数据库");
            importToDatabaseCheckbox.setSelected(true); // 默认选中
            buttonPanel.add(importToDatabaseCheckbox);

            frame.add(buttonPanel, BorderLayout.SOUTH);
        }

        public void appendText(String text) {
            SwingUtilities.invokeLater(() -> {
                textArea.append(text);
            });
        }
        public boolean isImportToDatabase() {
            return importToDatabaseCheckbox.isSelected();
        }
        public void display() {
            frame.setVisible(true);
        }
    }
}